package com.zeroext.show.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.zeroext.dao.common.BaseDAO;
import com.zeroext.dao.common.SimplePage;
import com.zeroext.show.dao.BookDAO;
import com.zeroext.show.entity.Book;

public class BookDAOImpl extends BaseDAO implements BookDAO {

    public Book getBook(Long id) {
        Session session = this.getSession();
        Criteria c = session.createCriteria(Book.class);
        c.add(Restrictions.eq("id", id));
        Book book = (Book)c.uniqueResult();
        return book;
    }

    public Book saveBook(Book book) {
        Session session = this.getSession();
        book = (Book) session.save(book);
        return book;
    }

    @SuppressWarnings("unchecked")
    public SimplePage<Book> searchBook(int begin, int pageSize,
            Map<String, Object> queryMap) {
        Session session = this.getSession();
        Criteria c = session.createCriteria(Book.class);
        if(queryMap != null){
            for(String pName : queryMap.keySet()){
                   c.add(Restrictions.eq(pName, queryMap.get(pName)));
            }
        }
        c.setFirstResult(begin);
        c.setMaxResults(pageSize);
        List<Book> books = c.list();
        long total = Long.valueOf(c.setProjection(Projections.rowCount()).uniqueResult().toString());
        SimplePage<Book> page = new SimplePage<Book>();
        page.setData(books);
        page.setTotal(total);
        return page;
    }

    @SuppressWarnings("unchecked")
    public List<Book> getBooksById(Long[] ids) {
        Session session = this.getSession();
        Criteria c = session.createCriteria(Book.class);
        c.add(Restrictions.in("id", ids));
        return c.list();
    }

    public void saveBook(List<Book> books) {
        Session session = this.getSession();
        for(Book book : books){
            session.save(book);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Book> getAllBook() {
        Session session = this.getSession();
        Criteria c = session.createCriteria(Book.class);
        return c.list();
    }

}
